package com.ace3l.legal.backend.web;

import com.ace3l.legal.Constants;
import com.ace3l.legal.backend.dao.ProjectDao;
import com.ace3l.legal.backend.dao.GeneralDao;
import com.ace3l.legal.backend.domain.User;
import com.ace3l.legal.backend.domain.Role;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.*;
import javax.servlet.http.*;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Created by IntelliJ IDEA.
 * User: ageer
 * Date: Jul 27, 2008
 * Time: 5:30:44 PM
 * To change this template use File | Settings | File Templates.
 */
public class SQLQueryServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        WebApplicationContext appCtx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        GeneralDao generalDao = (GeneralDao)appCtx.getBean("generalDao");

        String action = req.getParameter(Constants.ACTION);
        Map<String, Object> paramMap = new HashMap<String,Object>();
        Integer id = ((User)req.getSession().getAttribute(Constants.USERPROFILE)).getId();
        String role = (String)req.getSession().getAttribute(Constants.USERROLE);
        if (role.equals(Role.LAWFIRM)) {
            paramMap.put("lawFirmId", id);
        }
        if (role.equals(Role.STUDENT)) {
            paramMap.put("studentId", id);
        }

        List ret = generalDao.runNamedQuery(action,paramMap);
        
        XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
        
        String jsonString = xstream.toXML(ret);
        System.out.println(jsonString);
        Writer out = res.getWriter();
        out.write(jsonString);
        out.flush();
        out.close();
        
    }

    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        doGet(httpServletRequest, httpServletResponse);
    }
}
